"use strict";
cc._RF.push(module, '617b5KPPRpFBp3JOQImy4wR', 'Tools');
// scripts/util/Tools.ts

"use strict";
// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
Object.defineProperty(exports, "__esModule", { value: true });
exports.Tools = void 0;
var GlobalManagerController_1 = require("../GlobalManagerController");
var ToastController_1 = require("../ToastController");
var AudioManager_1 = require("./AudioManager");
var Config_1 = require("./Config");
var _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
var Tools = /** @class */ (function () {
    function Tools() {
    }
    Tools.setTouchEvent = function (peopleNode, startFunction, endFunction, cancelFunction) {
        this.setTouchEventParent(peopleNode, true, startFunction, endFunction, cancelFunction);
    };
    Tools.setGameTouchEvent = function (peopleNode, startFunction, endFunction, cancelFunction) {
        this.setTouchEventParent(peopleNode, false, startFunction, endFunction, cancelFunction);
    };
    //添加点击事件 
    //isSound 是否需要按键音效，大厅的都需要 游戏内有自己的按键音所以不需要
    //peopleNode 节点
    //startFunction 按下事件
    //endFunction 抬起事件
    //cancelFunction 取消事件
    Tools.setTouchEventParent = function (peopleNode, isSound, startFunction, endFunction, cancelFunction) {
        peopleNode.on(cc.Node.EventType.TOUCH_START, function (event) {
            if (isSound) {
                AudioManager_1.AudioManager.keyingToneAudio();
            }
            if (startFunction != null) {
                startFunction(peopleNode, event);
            }
        }, this);
        peopleNode.on(cc.Node.EventType.TOUCH_END, function (event) {
            if (endFunction != null) {
                endFunction(peopleNode, event);
            }
        }, this);
        peopleNode.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
            if (cancelFunction != null) {
                cancelFunction(peopleNode, event);
            }
        }, this);
    };
    Tools.cancelTouchStartListener = function (peopleNode) {
        peopleNode.off(cc.Node.EventType.TOUCH_START, this);
    };
    Tools.cancelTouchEndListener = function (peopleNode) {
        peopleNode.off(cc.Node.EventType.TOUCH_END, this);
    };
    Tools.cancelTouchCancelListener = function (peopleNode) {
        peopleNode.off(cc.Node.EventType.TOUCH_CANCEL, this);
    };
    //为精灵添加图片
    Tools.setNodeSpriteFrame = function (node, path) {
        cc.resources.load(path, cc.SpriteFrame, function (error, assets) {
            var sprite = node.getComponent(cc.Sprite);
            sprite.spriteFrame = assets;
        });
    };
    //添加网络图片
    Tools.setNodeSpriteFrameUrl = function (node, url) {
        if (!node) {
            console.error("setNodeSpriteFrameUrl: node 参数为空");
            return;
        }
        var avatarSp = node.getComponent(cc.Sprite);
        if (!avatarSp) {
            console.error("setNodeSpriteFrameUrl: 节点没有 cc.Sprite 组件", node.name);
            return;
        }
        if (url == null || url == '') {
            console.warn("setNodeSpriteFrameUrl: URL为空，跳过加载");
            return;
        }
        // 保存原有的材质，避免圆形遮罩丢失
        var originalMaterial = avatarSp.getMaterial(0);
        cc.assetManager.loadRemote(url, { ext: '.png' }, function (err, texture) {
            if (err) {
                console.error("加载远程图片失败：", err.message || err, "URL:", url);
                return;
            }
            texture.setPremultiplyAlpha(true);
            texture.packable = false; //加载圆头像的时候 必须关闭合图
            // 创建新的SpriteFrame并设置
            avatarSp.spriteFrame = new cc.SpriteFrame(texture);
            // 恢复原有的材质（保持圆形遮罩效果）
            if (originalMaterial) {
                avatarSp.setMaterial(0, originalMaterial);
            }
        });
    };
    //红色按钮
    Tools.redButton = function (node, click, label) {
        Tools.buttonState(node, Config_1.Config.btnRedNormal, Config_1.Config.btnRedPressed, Config_1.Config.btnRedNormalColor, Config_1.Config.btnRedPressedColor, click, label);
    };
    //绿色按钮
    Tools.greenButton = function (node, click, label) {
        Tools.buttonState(node, Config_1.Config.btnGreenNormal, Config_1.Config.btnGreenPressed, Config_1.Config.btnGreenNormalColor, Config_1.Config.btnGreenPressedColor, click, label);
    };
    //黄色按钮
    Tools.yellowButton = function (node, click, label) {
        Tools.buttonState(node, Config_1.Config.btnYellowNormal, Config_1.Config.btnYellowPressed, Config_1.Config.btnYellowNormalColor, Config_1.Config.btnYellowPressedColor, click, label);
    };
    //灰色按钮
    Tools.grayButton = function (node, click, label) {
        Tools.buttonState(node, Config_1.Config.btnGrayNormal, Config_1.Config.btnGrayNormal, Config_1.Config.btnGrayNormalColor, Config_1.Config.btnGrayNormalColor, click, label);
    };
    //通用的按钮点击事件，带点击变颜色的
    Tools.buttonState = function (node, normalImg, pressedImg, normalColor, pressedColor, click, labelText) {
        var btnGreen = node.getChildByName('btn_color_normal'); //获取按钮背景节点
        var btnLabel = node.getChildByName('button_label'); //获取按钮文字节点
        var label = btnLabel.getComponent(cc.Label);
        var labelOutline = btnLabel.getComponent(cc.LabelOutline);
        if (labelText != null) {
            label.string = labelText;
        }
        Tools.setTouchEvent(btnGreen, function (node) {
            Tools.setNodeSpriteFrame(node, pressedImg);
            label.fontSize = 34;
            label.lineHeight = 34;
            var color = new cc.Color();
            cc.Color.fromHEX(color, pressedColor);
            labelOutline.color = color;
            btnLabel.color = cc.Color.fromHEX(new cc.Color(), '#B3B3B3');
        }, function (node) {
            Tools.setNodeSpriteFrame(node, normalImg);
            label.fontSize = 36;
            label.lineHeight = 36;
            var color = new cc.Color();
            cc.Color.fromHEX(color, normalColor);
            labelOutline.color = color;
            btnLabel.color = cc.Color.fromHEX(new cc.Color(), '#FFFFFF');
            if (click != null) {
                click();
            }
        }, function (node) {
            Tools.setNodeSpriteFrame(node, normalImg);
            label.fontSize = 36;
            label.lineHeight = 36;
            var color = new cc.Color();
            cc.Color.fromHEX(color, normalColor);
            labelOutline.color = color;
            btnLabel.color = cc.Color.fromHEX(new cc.Color(), '#FFFFFF');
        });
    };
    //点击变颜色的图片按钮
    Tools.imageButtonClick = function (node, normalImg, pressedImg, click) {
        Tools.setTouchEvent(node, function (node) {
            Tools.setNodeSpriteFrame(node, pressedImg);
        }, function (node) {
            Tools.setNodeSpriteFrame(node, normalImg);
            click();
        }, function (node) {
            Tools.setNodeSpriteFrame(node, normalImg);
        });
    };
    //格式化资金显示格式的
    Tools.NumToTBMK = function (num, digit, min) {
        var _a;
        if (digit === void 0) { digit = 1; }
        if (min === void 0) { min = 10000; }
        var intNum = num;
        if (intNum < min) {
            return intNum.toString();
        }
        var unitStrArr = ["T", "B", "M", "K"];
        var unitArr = [Math.pow(10, 12), Math.pow(10, 9), Math.pow(10, 6), Math.pow(10, 3)];
        for (var i = 0; i < unitArr.length; ++i) {
            var result = intNum / unitArr[i];
            if (result >= 1) {
                var str = result.toString();
                var strArr = str.split(".");
                var suffix = (_a = strArr[1]) !== null && _a !== void 0 ? _a : "";
                if (suffix.length >= digit) {
                    if (digit == 0) {
                        return strArr[0] + unitStrArr[i];
                    }
                    return strArr[0] + "." + suffix.substring(0, digit) + unitStrArr[i];
                }
                else {
                    var fillStr = new Array(digit - suffix.length).fill("0").join("");
                    return strArr[0] + "." + suffix + fillStr + unitStrArr[i];
                }
            }
        }
    };
    Tools.getCurrentTimeWithMilliseconds = function () {
        var currentDate = new Date();
        var year = currentDate.getFullYear();
        var month = String(currentDate.getMonth() + 1).padStart(2, '0');
        var day = String(currentDate.getDate()).padStart(2, '0');
        var hours = String(currentDate.getHours()).padStart(2, '0');
        var minutes = String(currentDate.getMinutes()).padStart(2, '0');
        var seconds = String(currentDate.getSeconds()).padStart(2, '0');
        var milliseconds = String(currentDate.getMilliseconds()).padStart(3, '0');
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + "." + milliseconds;
    };
    //赋值文本到剪切板
    Tools.copyText = function (textToCopy, cb) {
        // 退回到使用 document.execCommand（旧版浏览器）
        var input = document.createElement('input');
        input.setAttribute('value', textToCopy);
        document.body.appendChild(input);
        // 选择文本并复制
        input.select();
        input.setSelectionRange(0, input.value.length); // 兼容移动端
        try {
            var successful = document.execCommand('copy');
            if (successful) {
                console.log("文本已复制到剪贴板！");
                cb && cb(true);
            }
            else {
                console.error("复制失败：execCommand 返回 false");
                cb && cb(false);
            }
        }
        catch (err) {
            console.error("复制失败：", err);
            cb && cb(false);
        }
        // 删除临时 input 元素
        document.body.removeChild(input);
    };
    //拆分数组用的，一个长度为 10 的数组 拆分成 2 个长度为 5 的数组 chunkArray(user_s, 5)
    Tools.chunkArray = function (arr, chunkSize) {
        var result = [];
        for (var i = 0; i < arr.length; i += chunkSize) {
            result.push(arr.slice(i, i + chunkSize));
        }
        return result;
    };
    //设置倒计时的秒数的位置
    Tools.setCountDownTimeLabel = function (buttonNode) {
        var btn = buttonNode.getChildByName('button_label');
        var timeBtn = buttonNode.getChildByName('buttonLabel_time');
        var xPos = btn.position.x + btn.width / 2 + timeBtn.width / 2;
        timeBtn.setPosition(xPos, 0);
    };
    //缩放+变暗按压效果的按钮
    Tools.scaleButtonClick = function (node, click) {
        // 保存原始状态
        var originalScale = node.scale;
        var originalColors = new Map();
        // 递归保存节点及其所有子节点的原始颜色
        var saveOriginalColors = function (targetNode) {
            originalColors.set(targetNode, targetNode.color.clone());
            targetNode.children.forEach(function (child) {
                saveOriginalColors(child);
            });
        };
        // 递归设置节点及其所有子节点的颜色
        var setNodeColors = function (targetNode, color) {
            targetNode.color = color;
            targetNode.children.forEach(function (child) {
                setNodeColors(child, color);
            });
        };
        // 递归恢复节点及其所有子节点的原始颜色
        var restoreOriginalColors = function (targetNode) {
            var originalColor = originalColors.get(targetNode);
            if (originalColor) {
                targetNode.color = originalColor;
            }
            targetNode.children.forEach(function (child) {
                restoreOriginalColors(child);
            });
        };
        // 保存所有节点的原始颜色
        saveOriginalColors(node);
        Tools.setTouchEvent(node, function (node) {
            // 按下时：缩放到0.95，所有节点颜色变暗到180（约70%亮度）
            cc.tween(node)
                .to(0.1, {
                scaleX: originalScale * 0.95,
                scaleY: originalScale * 0.95
            }, { easing: 'quadOut' })
                .start();
            setNodeColors(node, cc.color(180, 180, 180));
        }, function (node) {
            // 抬起时：恢复原始缩放和颜色，然后执行点击回调
            cc.tween(node)
                .to(0.1, {
                scaleX: originalScale,
                scaleY: originalScale
            }, { easing: 'backOut' })
                .start();
            restoreOriginalColors(node);
            if (click) {
                click();
            }
        }, function (node) {
            // 取消时：恢复原始状态
            cc.tween(node)
                .to(0.1, {
                scaleX: originalScale,
                scaleY: originalScale
            }, { easing: 'quadOut' })
                .start();
            restoreOriginalColors(node);
        });
    };
    //赋值文本到剪切板
    Tools.copyToClipboard = function (text) {
        var textarea = document.createElement('textarea');
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        try {
            var successful = document.execCommand('copy');
            if (successful) {
                console.log('文本已复制到剪切板');
                // 成功提示（多语言）
                // @ts-ignore
                var msg = typeof window.getLocalizedStr === 'function' ? window.getLocalizedStr('CopySuccess') : 'Copy success';
                this.showToast(msg);
            }
            else {
                console.error('复制到剪切板失败');
                // 失败提示（多语言）
                // @ts-ignore
                var msg = typeof window.getLocalizedStr === 'function' ? window.getLocalizedStr('CopyFailed') : 'Copy failed';
                this.showToast(msg);
            }
        }
        catch (err) {
            console.error('复制到剪切板失败：', err);
            // @ts-ignore
            var msg = typeof window.getLocalizedStr === 'function' ? window.getLocalizedStr('CopyFailed') : 'Copy failed';
            this.showToast(msg);
        }
        document.body.removeChild(textarea);
    };
    // 显示全局 Toast 提示
    Tools.showToast = function (content) {
        try {
            // 查找挂载了 GlobalManagerController 的节点（一般在 Canvas 上）
            var canvas = cc.find('Canvas');
            if (!canvas) {
                cc.warn('Canvas 节点未找到，无法显示 Toast');
                return;
            }
            var gm = canvas.getComponent(GlobalManagerController_1.default);
            if (gm && gm.toastController) {
                gm.toastController.showContent(content);
                return;
            }
            // 兜底：直接在 Canvas 子节点中查找任意一个 ToastController
            var toast = canvas.getComponentInChildren(ToastController_1.default);
            if (toast) {
                toast.showContent(content);
                return;
            }
            cc.warn('未找到可用的 ToastController 组件');
        }
        catch (e) {
            cc.warn('显示 Toast 失败: ', e);
        }
    };
    return Tools;
}());
exports.Tools = Tools;

cc._RF.pop();